pipeline {
    agent any

    parameters {
        gitParameter branch: '', branchFilter: 'origin/(.*)', defaultValue: 'master', description: '代码分支', name: 'gitlab_branch', quickFilterEnabled: false, selectedValue: 'DEFAULT', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH'
    }

    // 定义环境变量
    environment {
        APP_NAME = "my-node-app"
        REGISTRY = "your-docker-registry-url"
        DOCKER_IMAGE = "${REGISTRY}/${APP_NAME}"
    }

    stages {
        // 清理工作区
        stage('Clean') {
            steps {
                sh "rm -rf ${WORKSPACE} && mkdir -p ${WORKSPACE}"
            }
        }

        // 拉取代码阶段
        stage('Pull') {
            steps {
                git url: 'https://gitee.com/linux-lxf/java.git', branch: "${params.gitlab_branch}"
            }
        }

        // 打包项目阶段
        stage('Package') {
            steps {
                sh echo 'npm install'
            }
        }

        // 测试阶段
        stage('Test') {
            steps {
                sh echo 'test'
            }
        }

        // 构建 Docker 镜像阶段
        stage('Build Docker Image') {
            steps {
                echo 'docker build -t ${DOCKER_IMAGE}:${env.BUILD_NUMBER} .'
            }
        }

        // 推送 Docker 镜像阶段
        stage('Push Docker Image') {
            steps {
                // 假设已在 Jenkins 中配置好 Docker 仓库凭证
                withCredentials([usernamePassword(credentialsId: 'your-docker-credentials-id', passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
                    sh echo "docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD} ${REGISTRY}"
                }
                echo 'docker push ${DOCKER_IMAGE}:${env.BUILD_NUMBER}'
            }
        }

        // 部署阶段
        stage('Deploy') {
            steps {
                // 假设使用 kubectl 部署到 Kubernetes 集群，需根据实际情况修改
                echo '部署到 Kubernetes'
            }
        }
    }

    // 后置操作
    post {
        success {
            echo 'Pipeline completed successfully!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}